import React, { Component } from 'react';
import {messages} from "share/common";
import {Badge, Button, message, Modal, Icon} from "antd";
import financeViewService from "./corporate-payment-report-view.service";
import AdvancedTable from 'components/advanced-table'
import Info from 'components/info';
import ResizeTable from "components/resize-table";

class BatchDownload extends Component {

  componentWillReceiveProps(nextProps) {
    //切换tab时需要重新请求批次列表
    if (nextProps.tabKey === 'download') {
      this.advancedTableRef.getList();
    }
  }

  /**
   * 设置【生成pdf】【下载】【删除】按钮的loading状态
   * @param id: 批次号id
   * @param type: pdfLoading downloadLoading deleteLoading
   * @param isLoading: true false
   */
  setBtnLoading = (id, type, isLoading) => {
    const { loading } = this.state;
    loading[type][isLoading ? 'push' : 'delete'](id);
    this.setState({ loading });
  };

  //生成pdf
  generatePDF = (id) => {
    this.setBtnLoading(id, 'pdfLoading', true);
    financeViewService.generatePDF(id).then(() => {
      this.advancedTableRef.getList();
    }).catch(() => {
      this.setBtnLoading(id, 'pdfLoading', false)
    })
  };

  //下载批次
  downloadBatch = (id) => {
    this.setBtnLoading(id, 'downloadLoading', true);
    financeViewService.downloadBatch(id).then(res => {
      this.setBtnLoading(id, 'downloadLoading', false);
      window.open(res.data.fileURL)
    }).catch(() => {
      this.setBtnLoading(id, 'downloadLoading', false)
    })
  };

  //删除批次
  handleDeleteBatch = (id) => {
    this.setBtnLoading(id, 'deleteLoading', true);
    financeViewService.deleteBatch(id).then(() => {
      message.success(messages('common.delete.success',{arg1: ""})/*{arg1} 删除成功*/);
      this.setBtnLoading(id, 'deleteLoading', false);
      this.advancedTableRef.getList();
    }).catch(() => {
      this.setBtnLoading(id, 'deleteLoading', false)
    })
  };

  getColumns = loading => {
    return [{
      title: messages('expense-1.key584')/*批次号*/, dataIndex: 'expenseReportBatchId'
    }, {
      title: messages('finance-9.key101')/*单据数量*/, dataIndex: 'actualBatchSize', width: 120
    }, {
      title: messages('expense-1.key586')/*创建人工号*/, dataIndex: 'employeeID'
    }, {
      title: messages('expense-1.key587')/*创建人姓名*/, dataIndex: 'fullName'
    }, {
      title: messages('common.column.status')/*状态*/, dataIndex: 'status', width: 120,
      render: value => {
        switch(value) {
          case 0:
            return <Badge status="default" text={messages('expense-1.key588')/*未生成*/} />;
          case 1:
            return <Badge status="processing" text={messages('expense-1.key589')/*生成中*/} />;
          case 2:
            return <Badge status="success" text={messages('expense-1.key590')/*已生成*/} />;
          case 3:
            return <Badge status="error" text={messages('expense-1.key591')/*生成失败*/} />;
        }
      }
    }, {
      title: messages('common.operation')/*操作*/, dataIndex: 'id', width: 300,
      render: (value, record) => {
        return (
          <div className="batch-operate">
            <Button
              type="primary"
              className="margin-right-10 batch-operate-generating"
              disabled={record.status === 1 || loading.pdfLoading.indexOf(record.expenseReportBatchId) > -1}
              onClick={() => this.generatePDF(record.expenseReportBatchId)}
            >
              {record.status === 1 || loading.pdfLoading.indexOf(record.expenseReportBatchId) > -1
                ? messages('expense-1.key589')/*生成中*/
                : messages('expense-1.key592')/*生成PDF*/}
            </Button>
            <Button
              className="margin-right-10"
              disabled={record.status !== 2}
              loading={loading.downloadLoading.indexOf(record.expenseReportBatchId) > -1}
              onClick={() => this.downloadBatch(record.expenseReportBatchId)}
            >
              {messages('expense-1.key593')/*下载*/}
            </Button>
            <Button
              loading={loading.deleteLoading.indexOf(record.expenseReportBatchId) > -1}
              disabled={record.status === 1}
              onClick={() => {
                Modal.confirm({
                  title: messages('expense-1.key594')/*确认删除？*/,
                  content: messages('finance-9.key102')/*删除批次内的单据可重新生成批次*/,
                  onOk: () => this.handleDeleteBatch(record.expenseReportBatchId),
                })
              }}>
              {messages('common.delete')/*删除*/}
            </Button>
          </div>
        )
      }
    }]
  };

  advancedTableRef = null;

  state = {
    loading: {
      pdfLoading: [],
      downloadLoading: [],
      deleteLoading: []
    }
  };

  service = (page, size) => financeViewService.getBatchList({ page, size, corporateFlag: true });

  handleGetData = (data) => {
    data && data.map(item => {
      item.status !== 1 && this.setBtnLoading(item.expenseReportBatchId, 'pdfLoading', false);
    })
  };

  renderDesc = () => {
    return (
      <section style={{ float: 'right' }}>
        <div>1、{messages('finance-9.key103')/*单个批次中单据数量过大易导致打印失败，因此系统默认：100条/批*/}</div>
        <div>
          <span>2、{messages('expense-1.key597')/*【生成PDF】等待时间可能较长,请*/}</span>
          <a className="batch-title-refresh" onClick={() => this.advancedTableRef.getList()}>
            {messages('expense-1.key598')/*刷新*/}
          </a>
          <span>{messages('expense-1.key599')/*查看【生成PDF】是否已完成，在生成PDF期间您仍然可进行其他页面的操作。*/}</span>
        </div>
      </section>
    );
  };
  render() {
    const { loading } = this.state;
    return (
      <AdvancedTable.SimpleTable
        showUtils
        tableName="expense-batch-download-table"
        show={['table-utils']}
        index
        columns={this.getColumns(loading)}
        onRef={ref => this.advancedTableRef = ref}
        service={this.service}
        rowKey="id"
        onGetData={this.handleGetData}
      >
        <Info
          paragraph
          attributes={[{
            title: '',
            dataIndex: 'explain',
            span: 24,
            colon: false,
            widthFix: false,
            render: () => (
              <div className="batch-download-title">
                <div className="batch-download-title-title">
                  {messages('expense-1.key600')/*说明*/}：
                </div>
                <div>
                  {this.renderDesc()}
                </div>
              </div>
            )
          }]}
        />
      </AdvancedTable.SimpleTable>
    );
  }
}

export default BatchDownload;
